package source

import (
	"gitee.com/mjun1833/buildnotification/config"
	_ "github.com/lib/pq"
	"github.com/sirupsen/logrus"
	"sync"
	"xorm.io/xorm"
)

var (
	once     sync.Once
	instance *client
)

type client struct {
	engine *xorm.Engine
	conf   *Conf
}

func GetInstance() *client {
	once.Do(func() {
		conf := &Conf{}
		err := config.GetInstance().UnmarshalKey("base.db", conf)
		if err != nil {
			panic(err)
		}

		engine, err := xorm.NewEngine("postgres", conf.Addr)
		if err != nil {
			logrus.Errorf("[SOURCE_DB] new enigne err: %v", err)
			return
		}

		err = engine.Ping()
		if err != nil {
			logrus.Errorf("[SOURCE_DB] ping err: %v", err)
			return
		}

		engine.SetMaxOpenConns(conf.MaxOpenConns)
		engine.SetMaxIdleConns(conf.MaxIdleConns)
		engine.ShowSQL(conf.ShowSql)

		instance = &client{
			engine: engine,
			conf:   conf,
		}
	})

	return instance
}

func (c *client) GetDBEngine() *xorm.Engine {
	return c.engine
}
